// pages/goods_list/goods_list.js
import { request } from '../../request/index'
import regeneratorRuntime from '../../lib/runtime/runtime'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        index: 0,
        value: "综合",
        active: true
      },
      {
        index: 1,
        value: "销量",
        active: false
      },
      {
        index: 2,
        value: "价格",
        active: false
      },
    ],
    goodsList: []
  },
  queryParams: {
    query: '',
    cid: '',
    pagenum: 1,
    pagesize: 10
  },
  // 总页数
  totalPageNum: 0,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.queryParams.cid = options.cid || ''
    this.queryParams.query = options.query || ''
    this.getGoodsList()
  },
  tabsIndex(e) {
    const { index } = e.detail
    let { tabs } = this.data
    tabs.forEach((v, i) => i === index ? v.active = true : v.active = false)
    this.setData({
      tabs
    })
  },
  async getGoodsList() {
    const res = await request({ url: '/goods/search', data: this.queryParams })
    const total = res.total
    // 计算页数
    this.totalPageNum = Math.ceil(total / this.queryParams.pagesize)
    this.setData({
      goodsList: [...this.data.goodsList, ...res.goods]
    })
    wx.stopPullDownRefresh()
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.queryParams.pagenum >= this.totalPageNum) {
      wx.showToast({
        title: '亲，已经到底了哦~',
        icon: 'none',
      });
    } else {
      this.queryParams.pagenum++
      this.getGoodsList()
    }
  },
  // 监听页面下拉刷新
  onPullDownRefresh() {
    this.setData({
      goodsList: []
    })
    this.queryParams.pagenum = 1
    this.getGoodsList()
  }
})